# -*-encoding: utf-8 -*-

from pyramid.view import view_config
from pyramid.view import view_defaults
from pyramid.response import Response
from pyramid.httpexceptions import HTTPFound
import json
from ..utils.Hash.HashUtil import HashUtil
from ..utils.Image.ImageUtil import ImageUtil
from ..utils.DB import MySqlCRUD
import time, os, uuid, shutil, hashlib
import base64
from ..utils.Queue import UploadTasks
from ..utils.SMS import MobSMS
from ..utils.Cache.TokenCache import TokenCache
from ..utils.Cache.ChecksumCache import ChecksumCache
import logging

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
log = logging.getLogger(__name__)

from WebBase import Base

class Login(Base):
    @view_config(route_name='AppWebLoginRoute', renderer='../../templates/AppWebLogin.pt')
    def AppWebLoginRoute(self):
        return ''

    @view_config(route_name='AppWebLogoutRoute', request_method='GET')
    def AppWebLogoutRoute(self):
        self.request.session['tel'] = ''
        self.request.session['username'] = ''
        self.request.session['email'] = ''
        self.request.session['type'] = ''
        self.request.session['portrait'] = ''
        self.request.session['csc'] = ''
        self.request.session['tString'] = ''
        self.request.session['eString'] = ''
        self.request.session['tokenString'] = ''
        return HTTPFound(location='/AppWebIndex')

    @view_config(route_name='AppWebLoginVerifyRoute', request_method='POST')
    def AppWebLoginVerifyRoute(self):
        postParams =  self.request.POST
        tel = postParams.getone('tel')
        password = postParams.getone('password')
        password_digest = HashUtil.getStringMD5(password)
        log.debug('[WEBLOGIN][TEL]' + tel)
        log.debug('[WEBLOGIN][PASSWORD]' + password)
        log.debug('[WEBLOGIN][PASSWORD_DIGEST]' + password_digest)

        #sql = "select * from user_info where email = %s and password = %s"
        sql = "select username, email, tel, type, portrait from user_info where tel = %s and password = %s"
        result = MySqlCRUD.selectImpl(sql, tel, password_digest)
        log.debug(result)
        if result:
            username = result[0]['username']
            email = result[0]['email']
            type = result[0]['type']
            portrait = result[0]['portrait']
            map = {'email': email, 'username': username, 'type': type, 'portrait': portrait}

            timeString = self.getCurrentTimeString();
            tString = base64.b64encode(timeString)
            eString = HashUtil.getStringMD5(tel + tString)
            tokenString = self.calculateToken(tString, tel)

            log.debug(map)
            log.debug('tString:' + tString)
            log.debug('eString:' + eString)
            log.debug('tokenString:' + tokenString)

            timeString = str(time.time())
            cache = ChecksumCache()
            if not cache.addCache(tel, timeString):
                map = {'RetCode': '114', 'message': '登录流程验证失败!', 'data': '重新登录'}
                jsonStr = json.dumps(map, ensure_ascii=False)
                log.error(jsonStr)
                return HTTPFound(location='/')

            self.request.session['tel'] = tel
            self.request.session['username'] = username
            self.request.session['email'] = email
            self.request.session['type'] = type
            self.request.session['portrait'] = portrait.replace('/media', '/static')
            self.request.session['csc'] = timeString
            self.request.session['tString'] = tString
            self.request.session['eString'] = eString
            self.request.session['tokenString'] = tokenString
            return HTTPFound(location='/AppWebIndex')
        else:
            return HTTPFound(location='/')
